#ifndef SINGLETON_H
#define SINGLETON_H

#include <mutex>
#include <atomic>

template<typename T>
class Singleton {
public:
    // 删除拷贝构造和赋值运算符
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    // 方法1：双重检查锁定模式（线程安全）
    static T* getInstance() {
        T* tmp = instance.load(std::memory_order_acquire);
        if (tmp == nullptr) {
            std::lock_guard<std::mutex> lock(mutex);
            tmp = instance.load(std::memory_order_relaxed);
            if (tmp == nullptr) {
                tmp = new T();
                instance.store(tmp, std::memory_order_release);
            }
        }
        return tmp;
    }


protected:
    Singleton() = default;
    ~Singleton() = default;

private:
    static std::atomic<T*> instance;
    static std::mutex mutex;
};

template<typename T>
std::atomic<T*> Singleton<T>::instance{nullptr};

template<typename T>
std::mutex Singleton<T>::mutex;


#endif // SINGLETON_H
